package hairmember

import (
	"context"
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/hairmember"
	hairmemberReq "github.com/flipped-aurora/gin-vue-admin/server/model/hairmember/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	"gorm.io/gorm"
)

type MembersService struct{}

// CreateMembers 创建members表记录
// Author [yourname](https://github.com/yourname)
func (membersService *MembersService) CreateMembers(ctx context.Context, members *hairmember.Members) (err error) {
	// 设置Balance默认值0.00
	if members.Balance == nil {
		defaultBalance := 0.00
		members.Balance = &defaultBalance
	}

	// 设置Status默认值1（正常状态）
	if members.Status == nil {
		defaultStatus := int8(1)
		members.Status = &defaultStatus
	}

	// 设置MemberLevel默认值1（普通会员）
	if members.MemberLevel == nil {
		defaultLevel := int8(1)
		members.MemberLevel = &defaultLevel
	}

	// 设置TotalRecharge默认值0.00
	if members.TotalRecharge == nil {
		defaultTotalRecharge := 0.00
		members.TotalRecharge = &defaultTotalRecharge
	}

	// 设置TotalConsumption默认值0.00
	if members.TotalConsumption == nil {
		defaultTotalConsumption := 0.00
		members.TotalConsumption = &defaultTotalConsumption
	}

	// 设置创建和更新时间
	now := time.Now()
	members.CreatedAt = &now
	members.UpdatedAt = &now

	err = global.GVA_DB.Create(members).Error
	return err
}

// DeleteMembers 删除members表记录
// Author [yourname](https://github.com/yourname)
func (membersService *MembersService) DeleteMembers(ctx context.Context, id string) (err error) {
	err = global.GVA_DB.Delete(&hairmember.Members{}, "id = ?", id).Error
	return err
}

// DeleteMembersByIds 批量删除members表记录
// Author [yourname](https://github.com/yourname)
func (membersService *MembersService) DeleteMembersByIds(ctx context.Context, ids []string) (err error) {
	err = global.GVA_DB.Delete(&[]hairmember.Members{}, "id in ?", ids).Error
	return err
}

// UpdateMembers 更新members表记录
// Author [yourname](https://github.com/yourname)
func (membersService *MembersService) UpdateMembers(ctx context.Context, members hairmember.Members) (err error) {
	err = global.GVA_DB.Model(&hairmember.Members{}).Where("id = ?", members.Id).Updates(&members).Error
	return err
}

// GetMembers 根据id获取members表记录
// Author [yourname](https://github.com/yourname)
func (membersService *MembersService) GetMembers(ctx context.Context, id string) (members hairmember.Members, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&members).Error
	return
}

// GetMembersInfoList 分页获取members表记录
// Author [yourname](https://github.com/yourname)
func (membersService *MembersService) GetMembersInfoList(ctx context.Context, info hairmemberReq.MembersSearch) (list []hairmember.Members, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&hairmember.Members{})
	var memberss []hairmember.Members
	// 如果有条件搜索 下方会自动创建搜索语句

	// 按会员名称过滤
	if info.MemberName != "" {
		db = db.Where("member_name LIKE ?", "%"+info.MemberName+"%")
	}
	// 按手机号过滤
	if info.Phone != "" {
		db = db.Where("phone LIKE ?", "%"+info.Phone+"%")
	}
	// 按会员等级过滤
	if info.MemberLevel > 0 {
		db = db.Where("member_level = ?", info.MemberLevel)
	}
	// 按状态过滤
	if info.Status > 0 {
		db = db.Where("status = ?", info.Status)
	}
	// 根据日期范围过滤 startDate默认为0:0:0 endDate默认为23:59:59
	if info.StartDate != "" {
		db = db.Where("created_at >= ?", info.StartDate)
	}
	if info.EndDate != "" {
		db = db.Where("created_at <= ?", info.EndDate+" 23:59:59")
	}
	// 按余额范围过滤
	if info.BalanceRange != "" && info.BalanceRange != "all" {
		// 检查是否是范围格式（如：0-1000）
		if strings.Contains(info.BalanceRange, "-") {
			rangeParts := strings.Split(info.BalanceRange, "-")
			if len(rangeParts) == 2 {
				minBalance := strings.TrimSpace(rangeParts[0])
				maxBalance := strings.TrimSpace(rangeParts[1])
				if minBalance != "" && maxBalance != "" {
					// 有最小值和最大值
					db = db.Where("balance >= ? AND balance <= ?", minBalance, maxBalance)
				} else if minBalance != "" {
					// 只有最小值
					db = db.Where("balance >= ?", minBalance)
				} else if maxBalance != "" {
					// 只有最大值
					db = db.Where("balance <= ?", maxBalance)
				}
			}
		} else {
			// 保持原有逻辑，兼容旧格式
			switch info.BalanceRange {
			case "negative":
				db = db.Where("balance < 0")
			case "zero":
				db = db.Where("balance = 0")
			case "positive":
				db = db.Where("balance > 0")
			}
		}
	}

	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&memberss).Error
	return memberss, total, err
}
func (membersService *MembersService) GetMembersPublic(ctx context.Context) {
	// 此方法为获取数据源定义的数据
	// 请自行实现
}

// GetMemberRechargeList 获取会员充值记录列表
// Author [yourname](https://github.com/yourname)
func (membersService *MembersService) GetMemberRechargeList(ctx context.Context, query request.MemberConsumptionQuery) (list interface{}, total int64, err error) {
	limit := query.PageSize
	offset := query.PageSize * (query.Page - 1)

	// 查询充值记录，通过会员名称和手机号过滤
	db := global.GVA_DB.Model(&model.RechargeRecord{}).
		Joins("JOIN members ON members.id = recharge_records.member_id")

	// 根据会员名称过滤
	if query.MemberName != "" {
		db = db.Where("members.member_name LIKE ?", "%"+query.MemberName+"%")
	}

	// 根据手机号过滤
	if query.Phone != "" {
		db = db.Where("members.phone LIKE ?", "%"+query.Phone+"%")
	}

	// 根据日期范围过滤 startDate默认为0:0:0 endDate默认为23:59:59
	if query.StartDate != "" {
		db = db.Where("recharge_time >= ?", query.StartDate)
	}
	if query.EndDate != "" {
		db = db.Where("recharge_time <= ?", query.EndDate+" 23:59:59")
	}

	// 查询记录总数
	err = db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 查询充值记录并关联会员信息
	db = db.Select("recharge_records.*, members.member_name, members.phone")

	var rechargeList []struct {
		model.RechargeRecord
		MemberName string `gorm:"column:member_name"`
		Phone      string `gorm:"column:phone"`
	}
	err = db.Limit(limit).Offset(offset).Order("id desc").Find(&rechargeList).Error
	if err != nil {
		return nil, 0, err
	}

	// 构建返回数据，添加前端需要的字段
	type RechargeRecordResp struct {
		model.RechargeRecord
		MemberName   string `json:"memberName"`
		Phone        string `json:"phone"`
		OperatorName string `json:"operatorName"`
	}

	var resultList []RechargeRecordResp
	for _, record := range rechargeList {
		resp := RechargeRecordResp{
			RechargeRecord: record.RechargeRecord,
			MemberName:     record.MemberName,
			Phone:          record.Phone,
		}

		// 获取操作员信息
		if record.OperatorID > 0 {
			var user system.SysUser
			if err = global.GVA_DB.Where("id = ?", record.OperatorID).First(&user).Error; err == nil {
				resp.OperatorName = user.NickName
			}
		}

		resultList = append(resultList, resp)
	}

	return resultList, total, err
}

// RechargeMember 会员充值
// Author [yourname](https://github.com/yourname)
func (membersService *MembersService) RechargeMember(ctx context.Context, recharge model.MemberRecharge, operatorID uint64) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		// 获取会员信息
		var member hairmember.Members
		if err := tx.Where("id = ?", recharge.MemberID).First(&member).Error; err != nil {
			return err
		}

		// 获取会员等级信息
		var levelInfo model.MemberLevel
		if err := tx.Where("level_code = ?", member.MemberLevel).First(&levelInfo).Error; err != nil {
			return err
		}

		// 计算赠送金额
		giftAmount := recharge.RechargeAmount * levelInfo.RechargeGiftRate
		finalAmount := recharge.RechargeAmount + giftAmount

		// 获取当前值（处理指针类型）
		currentBalance := 0.0
		if member.Balance != nil {
			currentBalance = *member.Balance
		}
		currentTotalRecharge := 0.0
		if member.TotalRecharge != nil {
			currentTotalRecharge = *member.TotalRecharge
		}
		currentMemberLevel := int8(1)
		if member.MemberLevel != nil {
			currentMemberLevel = *member.MemberLevel
		}

		// 更新会员余额和累计充值
		newBalance := currentBalance + finalAmount
		newTotalRecharge := currentTotalRecharge + recharge.RechargeAmount

		// 检查是否需要升级会员等级
		var newLevelInfo model.MemberLevel
		if err := tx.Where("min_recharge <= ?", newTotalRecharge).
			Order("min_recharge desc").First(&newLevelInfo).Error; err == nil {
			if int8(newLevelInfo.LevelCode) > currentMemberLevel {
				currentMemberLevel = int8(newLevelInfo.LevelCode)
			}
		}

		member.Balance = &newBalance
		member.TotalRecharge = &newTotalRecharge
		member.MemberLevel = &currentMemberLevel

		if err := tx.Save(&member).Error; err != nil {
			return err
		}

		// 创建充值记录
		orderNo := fmt.Sprintf("RC%s%09d", time.Now().Format("20060102-150405"), recharge.MemberID)
		rechargeRecord := model.RechargeRecord{
			OrderNo:        orderNo,
			MemberID:       recharge.MemberID,
			RechargeAmount: recharge.RechargeAmount,
			GiftAmount:     giftAmount,
			FinalAmount:    finalAmount,
			PaymentMethod:  recharge.PaymentMethod,
			BalanceBefore:  currentBalance,
			BalanceAfter:   newBalance,
			OperatorID:     operatorID,
			Remark:         recharge.Remark,
			RechargeTime:   time.Now(),
		}

		if err := tx.Create(&rechargeRecord).Error; err != nil {
			return err
		}

		return nil
	})
}

// ConsumeMember 会员消费扣费
// Author [yourname](https://github.com/yourname)
func (membersService *MembersService) ConsumeMember(ctx context.Context, consumption model.MemberConsumption, operatorID uint64) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		// 获取会员信息
		var member hairmember.Members
		if err := tx.Where("id = ?", consumption.MemberID).First(&member).Error; err != nil {
			return err
		}

		// 获取当前余额（处理指针类型）
		currentBalance := 0.0
		if member.Balance != nil {
			currentBalance = *member.Balance
		}

		// 检查余额是否充足
		if currentBalance < consumption.ConsumptionAmount {
			return errors.New("会员余额不足")
		}

		// 获取会员等级信息
		var levelInfo model.MemberLevel
		if err := tx.Where("level_code = ?", member.MemberLevel).First(&levelInfo).Error; err != nil {
			return err
		}

		// 计算折扣后金额
		discountRate := levelInfo.DiscountRate
		if discountRate <= 0 || discountRate > 1 {
			discountRate = 1.0
		}
		finalAmount := consumption.ConsumptionAmount * discountRate

		// 更新会员余额、累计消费和最近消费时间
		newBalance := currentBalance - finalAmount
		currentTotalConsumption := 0.0
		if member.TotalConsumption != nil {
			currentTotalConsumption = *member.TotalConsumption
		}
		// 使用实际扣费金额（折扣后）更新累计消费，而不是原始消费金额
		newTotalConsumption := currentTotalConsumption + finalAmount

		member.Balance = &newBalance
		member.TotalConsumption = &newTotalConsumption
		now := time.Now()
		member.LastConsumptionTime = &now

		if err := tx.Save(&member).Error; err != nil {
			return err
		}

		// 创建消费记录
		orderNo := fmt.Sprintf("CO%s%09d", time.Now().Format("20060102-150405"), consumption.MemberID)
		consumptionRecord := model.ConsumptionRecord{
			OrderNo:           orderNo,
			MemberID:          consumption.MemberID,
			ConsumptionAmount: consumption.ConsumptionAmount,
			FinalAmount:       finalAmount,
			ProjectType:       consumption.ProjectType,
			ProjectName:       consumption.ProjectName,
			DiscountRate:      discountRate,
			BalanceBefore:     currentBalance,
			BalanceAfter:      newBalance,
			OperatorID:        operatorID,
			Remark:            consumption.Remark,
			ConsumptionTime:   time.Now(),
		}

		if err := tx.Create(&consumptionRecord).Error; err != nil {
			return err
		}

		return nil
	})
}

// GetMemberConsumptionList 获取会员消费记录列表
// Author [yourname](https://github.com/yourname)
func (membersService *MembersService) GetMemberConsumptionList(ctx context.Context, query request.MemberConsumptionQuery) (list interface{}, total int64, err error) {
	limit := query.PageSize
	offset := query.PageSize * (query.Page - 1)

	// 查询消费记录，通过会员名称和手机号过滤
	db := global.GVA_DB.Model(&model.ConsumptionRecord{}).
		Joins("JOIN members ON members.id = consumption_records.member_id")

	// 根据会员名称过滤
	if query.MemberName != "" {
		db = db.Where("members.member_name LIKE ?", "%"+query.MemberName+"%")
	}

	// 根据手机号过滤
	if query.Phone != "" {
		db = db.Where("members.phone LIKE ?", "%"+query.Phone+"%")
	}

	// 根据日期范围过滤
	if query.StartDate != "" {
		db = db.Where("consumption_time >= ?", query.StartDate)
	}
	if query.EndDate != "" {
		db = db.Where("consumption_time <= ?", query.EndDate+" 23:59:59")
	}

	// 查询记录总数
	err = db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 查询消费记录并关联会员信息
	db = db.Select("consumption_records.*, members.member_name, members.phone")

	var consumptionList []struct {
		model.ConsumptionRecord
		MemberName string `gorm:"column:member_name"`
		Phone      string `gorm:"column:phone"`
	}
	err = db.Limit(limit).Offset(offset).Order("consumption_time desc").Find(&consumptionList).Error
	if err != nil {
		return nil, 0, err
	}

	// 构建返回数据，添加前端需要的字段
	type ConsumptionRecordResp struct {
		model.ConsumptionRecord
		MemberName   string `json:"memberName"`
		Phone        string `json:"phone"`
		OperatorName string `json:"operatorName"`
	}

	var resultList []ConsumptionRecordResp
	for _, record := range consumptionList {
		resp := ConsumptionRecordResp{
			ConsumptionRecord: record.ConsumptionRecord,
			MemberName:        record.MemberName,
			Phone:             record.Phone,
		}

		// 获取操作员信息
		if record.OperatorID > 0 {
			var user system.SysUser
			if err := global.GVA_DB.Where("id = ?", record.OperatorID).First(&user).Error; err == nil {
				resp.OperatorName = user.NickName
			}
		}

		resultList = append(resultList, resp)
	}

	return resultList, total, err
}
